/*
 * Middleware
 * Copyright (C) 2010/11
 * Riccardo Pulvirenti, Giuseppe Ravidà, Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: synlogger.cpp
 */

#include <iostream>
#include <string>
#include <exception>
#include <ios>

#include "synlogger.hpp"

using namespace middleware;

//-----------------------------------------------------------------------------
// Constructors and destructor
/* Default constructor */
SynLogger::SynLogger() {
	this->_log_tag = "log";
	this->_log_filename = "log.middleware.log";
}
/* Constructor */
SynLogger::SynLogger(std::string logname, std::string logtag) {
	this->_log_tag = logtag;
	this->_log_filename = logname + std::string(".middleware.log");
}
/* Copy constructor */
SynLogger::SynLogger(const SynLogger& logger) {
	this->_log_filename = logger._log_filename;
	this->_log_tag = logger._log_tag;
}
/* Destructor */
SynLogger::~SynLogger() {

}
/* Printing */
void SynLogger::Print(std::string logstring) {
	time_t rawtime;
	struct tm* timeinfo;
	time (&rawtime);
	timeinfo = localtime(&rawtime);
	boost::mutex::scoped_lock lck(this->_print_monitor); /* Locks mutex */
	this->Open();
	this->_log_file << _log_tag << ": " << timeinfo->tm_mday << "/"
			<< timeinfo->tm_mon + 1 << "/"
			<< timeinfo->tm_year + 1900 << "#"
			<< timeinfo->tm_hour << "."
			<< timeinfo->tm_min << "."
			<< timeinfo->tm_sec << " ==> " << logstring << std::endl;
	this->Close();
	lck.unlock();
}
//-----------------------------------------------------------------------------
// Private members
/* Open file */
void SynLogger::Open() {
	// Attempt open for read
	this->_log_file.open(this->_log_filename.c_str(), std::ios_base::in);
	if (!(this->_log_file))	{
		// File doesn't exist; create a new one
		this->_log_file.open(_log_filename.c_str(), std::ios_base::out);
	} else {
		// Ok, file exists; close and reopen in write mode
		this->_log_file.close();
		this->_log_file.open(this->_log_filename.c_str(), std::ios_base::out |
				std::ios::app); // reopen for write
	}
}
/* Close file */
void SynLogger::Close() {
	this->_log_file.close();
}


